# -*- coding:utf-8 -*-
from bluepy import btle
from bluepy.btle import Scanner, DefaultDelegate
import prettytable as pt
import time
import eventlet

class ScanDelegate(DefaultDelegate):
    def __init__(self):
        DefaultDelegate.__init__(self)

    def handleDiscovery(self, dev, isNewDev, isNewData):
        if isNewDev:
            print "Discovered device", dev.addr
        elif isNewData:
            print "Received new data from", dev.addr
class Ble:
    def __init__(self, addr, addrType):
        self.addr = addr
        self.addrType = addrType

    def getInfo(self):
        # if properties=='READ', readType and readMsg
        info = {} # {service1:{chara1:[handle, properties, readType, readMsg], chara2}}
        try:
            d = btle.Peripheral(self.addr, self.addrType)
        except:
            print 'connect failed......'
            return 1
        try:
            for ser in d.getServices():
                dict1 = {}
                #eventlet.monkey_patch()
                #with eventlet.Timeout(2, False):
                   # time.sleep(5)
                    # 获取不到设备信息，卡在这里了，尝试使用超时时间来跳过
                for chara in ser.getCharacteristics():
                    list1 = []
                    list1.append(str(chara.getHandle()))
                    list1.append(chara.propertiesToString())
                    if (chara.supportsRead()):
                        list1.append(type(chara.read()))
                        list1.append(chara.read())
                    dict1[str(chara)] = list1
                info[str(ser)] = dict1
        except:
            pass
        d.disconnect()
        return info

if __name__ == '__main__':
    scanner = Scanner().withDelegate(ScanDelegate())
    devices = scanner.scan()
    tb = pt.PrettyTable()
    tb.field_names = ["MAC", "MAC类型", "信号强度", "Flags", "厂商", "服务(UUID)", "属性", "handle", "ch_type", "detail"]
    for dev in devices:

        print '**************************************************************************'
        print "Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi)
        print dev.getScanData()
        for (adtype, desc, value) in dev.getScanData():
            print "  %s = %s" % (desc, value)
        services = ''
        try:
            info = Ble(dev.addr, dev.addrType).getInfo()

            print '---------',info
            if info == 1 or info == 2:
                print 'the host is down...'
            else:
                for k, v in info.items():
                    print '*************************************************************************************************'
                    print '>>>>', k.split('<')[1].split('>')[0]
                    if v:
                        for ch, detail in v.items():
                            print '>>>>>>>>>>>', ch
                           # print detail.split('<')
                            tb.add_row([dev.addr, dev.addrType, dev.rssi, dev.getScanData()[0][2], dev.getScanData()[1][2], k.split('<')[1].split('>')[0], ch.split('<')[1].split('>')[0], detail[0], detail[1], detail])
            print tb
        except OSError:
            pass
        continue